<?php

namespace App\Module;

use App\depository\ManagePlayerDep;
use App\depository\ManageSecretDep;
use App\depository\PlayerSecretDep;
use App\depository\RecordFlyDep;
use App\depository\SteamIDEosidDep;
use App\depository\ManageForbiddenDep;
use App\depository\SubAuthorityDep;
use App\depository\TeamDictDep;
use App\depository\TeamsDep;
use App\depository\ManageCMDDep;
use App\Enum\CommonEnum;
use http\Client;
use Illuminate\Support\Facades\URL;
use App\depository\SubCfgDep;

class GameModule extends BaseModule
{
    public function manageplayer_add($request)
    {
        $params = $request->all();

//        log_daily(__FUNCTION__)->info(json_encode($params, JSON_UNESCAPED_UNICODE));
        $SteamIDEosidDep = new SteamIDEosidDep;
        $ManagePlayerDep = new ManagePlayerDep;
        $gh_id = $params['gh_id'];
        $gh_secret = $params['gh_secret'];
        $res = (new TeamsDep)->check_exists($gh_id, $gh_secret);
        if (is_null($res)) {
            return self::response([], "工会ID与密钥不匹配", 2);
        }

        $manage_player_datas = [];
        $steamData = [];
        foreach ($params['Players'] as $v) {
            $playerid = $v['id'];
            $steamid = $v['SteamId'];
            $eosid = $v['EosId'];
            $name = $v['Name'];
            $team_id = $v['TeamID'];
            $team_name = $v['TeamName'];
            $squad_name = $v['SquadName'];
            $squad_id = $v['SquadID'];
            $is_leader = $v['IsLeader'];
            $role = $v['Role'];

            $steam_eos = $SteamIDEosidDep->get_fields(['*'], 'steamid', $steamid);
            if(!$steam_eos && $steamid && $eosid){
                $steamData[] = [
                    'steamid' => $steamid,
                    'eosid' => $eosid,
                    'status' => SteamIDEosidDep::STATUS_ON
                ];
            }

            $manage_player_datas[] = [
                'playerid' => $playerid,
                'gh_id' => $gh_id,
                'steamid' => $steamid,
                'eosid' => $eosid,
                'name' => $name,
                'team_id' => $team_id,
                'team_name' => $team_name,
                'squad_id' => $squad_id,
                'squad_name' => $squad_name,
                'is_leader' => $is_leader,
                'role' => $role
            ];
        }
        $ManagePlayerDep->del_by_gh_id($gh_id);
        $ManagePlayerDep->add($manage_player_datas);
        $SteamIDEosidDep->add($steamData);

        return self::response();
    }

    public function manageplayer_get($request)
    {
        $params = $request->all();
//        log_daily(__FUNCTION__)->info(json_encode($params, JSON_UNESCAPED_UNICODE));
        $num = $params['num'] > 200 ? 200 : $params['num'];
        $ManagePlayerDep = new ManagePlayerDep;
        try {
            $res = $ManagePlayerDep->get_list($num)->toArray();
        } catch (\Exception $e) {
            log_daily(__FUNCTION__)->info($e->getMessage());
        }
        return self::response($res);
    }

    public function managesecret_add($request)
    {
        $params = $request->all();
//        log_daily(__FUNCTION__)->info(json_encode($params, JSON_UNESCAPED_UNICODE));

        $steamid = $params['steamid'];
        $days = $params['days'];
        $group_name = $params['group_name'];
        $gh_id = $params['gh_id'];
        $extra = $params['extra'];

        $secret = create_secret();

        $secretDep = new ManageSecretDep();
        $activeDep = new PlayerSecretDep();
        if(!$steamid){
            $secretData = [
                'gh_id' => $gh_id,
                'secret' => $secret,
                'days' => $days,
                'status' => ManageSecretDep::STATUS_OFF,
                'group_name' => $group_name,
                'extra' => $extra,
            ];
            $secretDep->add($secretData);
            return  self::response(['secret' => $secret, 'steamid' => "", 'datetime' => ""]);
        }

        $data = [
            'gh_id' => $gh_id,
            'secret' => $secret,
            'steamid' => $steamid,
            'days' => $days,
            'status' => ManageSecretDep::STATUS_ON,
            'group_name' => $group_name,
            'extra' => $extra,
        ];
        $secretDep->add($data);

        $resActive = $activeDep->firstBySteamId($gh_id,$steamid);
        if(!$resActive){
            $activeData = [
                'steamid' => $steamid,
                'team_id' => $gh_id,
                'group' => $group_name,
                'start_at' =>  date("Y-m-d H:i:s"),
                'end_at' => date("Y-m-d H:i:s", strtotime("+{$days} days")),
            ];
            $activeDep->add($activeData);
        }else{
            $activeData = [
                'end_at' => date("Y-m-d H:i:s", strtotime("+{$days} days",strtotime($resActive->end_at))),
            ];
            $activeDep->upd($resActive->id,$activeData);
        }

        return self::response(['secret' => $secret, 'steamid' => $steamid, 'datetime' => $activeData['end_at']]);
    }

    public function manageforbidden_add($request)
    {
        $params = $request->all();
//        log_daily(__FUNCTION__)->info(json_encode($params, JSON_UNESCAPED_UNICODE));
        $steamid = $params['steamid'];
        $eosid = $params['eosid'];
        $reason = $params['reason'];
        $days = $params['days'] == 0 ? 100000 : $params['days'];
        $gh_id = $params['gh_id'];
        $gh_secret = $params['gh_secret'];
        try {
            $res = (new TeamsDep)->check_exists($gh_id, $gh_secret);
            if (is_null($res)) {
                return self::response([], "工会ID与密钥不匹配", 2);
            }
            $SteamIDEosidDep = new SteamIDEosidDep;
            if (!$steamid && $eosid) {
                $steamid = $SteamIDEosidDep->get_fields(['steamid'], 'eosid', $eosid)->steamid ?? "";
            }
            if (!$eosid && $steamid) {
                $eosid = $SteamIDEosidDep->get_fields(['eosid'], 'steamid', $steamid)->eosid ?? "";
            }
            $data = [
                'user_name' => 'api',
                'nick_name' => "api",
                'steamid' => $steamid,
                'eosid' => $eosid,
                'days' => $days,
                'reason' => $reason,
                'status' => ManageForbiddenDep::STATUS_THREE,
                'start_time' => date("Y-m-d H:i:s"),
                'end_time' => $days == 0 ? "2298-01-01 00:00:00" : date("Y-m-d H:i:s", strtotime("+{$days} days")),
                'gh_id' => $gh_id
            ];
            (new ManageForbiddenDep)->add($data);

            $dictDep = new TeamDictDep();
            $resDict = $dictDep->getByTeamId($gh_id);

            $rcon = $resDict->first(function ($item) {
                return $item->label == 'RCON地址';
            });

            if ($rcon) {
                $text = $reason ?: '{理由}';
                $str = str_replace('{理由}', $reason, $text);
                $str = str_replace('{名称}', 'api', $str);

                $client = new \GuzzleHttp\Client();
                $url = $rcon->value . "AdminBan {$steamid} {$days} {$str}";
                $client->get($url);
            }
        } catch (\Exception $e) {
            log_daily(__FUNCTION__)->info($e->getMessage());
        }
        return self::response();
    }

    public function manageforbidden_get($request)
    {
        $params = $request->all();
//        log_daily(__FUNCTION__)->info(json_encode($params, JSON_UNESCAPED_UNICODE));
        $steamid = $params['steamid'];
        try {

            $res = (new ManageForbiddenDep)->get_list_by_steamid($steamid);

        } catch (\Exception $e) {
            log_daily(__FUNCTION__)->info($e->getMessage());
        }
        return self::response($res);
    }

    public function managecmd_add($request)
    {
        $params = $request->all();
//        log_daily(__FUNCTION__)->info(json_encode($params, JSON_UNESCAPED_UNICODE));
        $time = $params['time'];
        $ip = $params['ip'];
        $content = $params['content'];
        $gh_id = $params['gh_id'];
        $gh_secret = $params['gh_secret'];

        try {
            $res = (new TeamsDep)->check_exists($gh_id, $gh_secret);
            if (is_null($res)) {
                return self::response([], "工会ID与密钥不匹配", 2);
            }
            $data = [
                'time' => $time,
                'team_id' => $gh_id,
                'ip' => $ip,
                'content' => $content,
            ];
            (new ManageCMDDep)->add($data);
        } catch (\Exception $e) {
            log_daily(__FUNCTION__)->info($e->getMessage());
        }
        return self::response();
    }

    public function managecmd_send($request)
    {
        $params = $request->all();

        return self::response(["cmd" => $params['cmd']]);
    }

    public function manageforbidden_cfg($request)
    {
        $params = $request->all();
        $gh_id = $params['gh_id'];
        $gh_secret = $params['gh_secret'];
        $res = (new TeamsDep)->check_exists($gh_id, $gh_secret);
        if (is_null($res)) {
            return self::response([], "工会ID与密钥不匹配", 2);
        }
        $list = (new ManageForbiddenDep)->get_list_by_status($gh_id);
        @mkdir(public_path("cfg"));
        $file_name = "cfg/ban_{$gh_id}" . date("YmdHis") . ".cfg";
        $cfg = public_path($file_name);
        $res = fopen($cfg, "a+");
        foreach ($list as $val) {
            fwrite($res, "{$val['steamid']}:0\r\n");
        }
        fclose($res);
//        return self::response(["url" => URL::to('/') . "/{$file_name}"]);
        return self::response(["url" => env("APP_URL") . "/{$file_name}"]);
    }

    public function example_cfg($request)
    {
        $params = $request->all();
        $gh_id = $params['gh_id'];
        $gh_secret = $params['gh_secret'];
        $name = $params['name'];
        $res = (new TeamsDep)->check_exists($gh_id, $gh_secret);
        if (is_null($res)) {
            return self::response([], "工会ID与密钥不匹配", 2);
        }
        $content = (new SubCfgDep)->get_contents($gh_id, $name);
        if (is_null($content)) return self::response([], '无数据', 0);
        @mkdir(public_path("cfg"));
        $file_name = "cfg/ban_{$gh_id}" . date("YmdHis") . ".cfg";
        $cfg = public_path($file_name);
        file_put_contents($cfg, $content->content);
//        return self::response(["url" => URL::to('/') . "/{$file_name}"]);
        return self::response(["url" => env("APP_URL") . "/{$file_name}"]);
    }

    public function system_get($request)
    {

        $params = $request->all();
        $gh_id = $params['gh_id'];
        $gh_secret = $params['gh_secret'];
        $res = (new TeamsDep)->check_exists($gh_id, $gh_secret);
        if (is_null($res)) {
            return self::response([], "工会ID与密钥不匹配", 2);
        }
        $data = [
            'is_open' => $res->is_open,
            'is_update' => $res->is_update,
        ];
        return self::response($data);
    }

    public function system_add($request)
    {

        $params = $request->all();
        $gh_id = $params['gh_id'];
        $gh_secret = $params['gh_secret'];
        $status = $params['status'];
        $version = $params['version'];

        $dep = new TeamsDep();
        $res = $dep->check_exists($gh_id, $gh_secret);
        if (is_null($res)) {
            return self::response([], "工会ID与密钥不匹配", 2);
        }

        if($status == 1){
            $data = [
                'open_desc' => "服务器开启 - " . date("Y-m-d H:i:s"),
            ];
        }elseif($status == 2){
            $data = [
                'open_desc' => "服务器关闭 - " . date("Y-m-d H:i:s"),
            ];
        }elseif($status == 3){
            $data = [
                'update_desc' => "服务器更新中 - " . date("Y-m-d H:i:s"),
            ];
        }elseif($status == 4){
            $data = [
                'update_desc' => "服务器更新失败 - " . date("Y-m-d H:i:s"),
                'is_update' => CommonEnum::NO
            ];
        }elseif ($status == 5){
            $data = [
                'update_desc' => "服务器更新成功 - " . date("Y-m-d H:i:s"),
                'is_update' => CommonEnum::NO
            ];
        }

        $data['version'] = $version;
        $dep->upd($res->id, $data);

        return self::response($data);
    }

    public function managesecret_cfg($request){

        $params = $request->all();
        $gh_id = $params['gh_id'];
        $gh_secret = $params['gh_secret'];
        $res = (new TeamsDep)->check_exists($gh_id, $gh_secret);
        if (is_null($res)) {
            return self::response([], "工会ID与密钥不匹配", 2);
        }

        $secretGroup = $res->secret_group;


        $dep = new PlayerSecretDep();
        $list = $dep->getByTeamId($gh_id);

        @mkdir(public_path("cfg"));

        $file_name = "cfg/secret_{$gh_id}" . date("YmdHis") . ".cfg";
        $cfg = public_path($file_name);
        $res = fopen($cfg, "a+");
        fwrite($res,$secretGroup);
        fwrite($res,"\n\n");
        foreach ($list as $val) {
            fwrite($res, "Admin={$val['steamid']}:{$val['group']}\r\n");
        }
        fclose($res);
//        return self::response(["url" => URL::to('/') . "/{$file_name}"]);
        return self::response(["url" => env("APP_URL") . "/{$file_name}"]);
    }

    public function managePermission_cfg($request){

        $params = $request->all();
        $gh_id = $params['gh_id'];
        $gh_secret = $params['gh_secret'];
        $res = (new TeamsDep)->check_exists($gh_id, $gh_secret);
        if (is_null($res)) {
            return self::response([], "工会ID与密钥不匹配", 2);
        }

        $secretGroup = $res->permission_group;
        $secretDep = new SubAuthorityDep();

        $list = $secretDep->getByTeamId($gh_id);

        @mkdir(public_path("cfg"));

        $file_name = "cfg/auth_{$gh_id}" . date("YmdHis") . ".cfg";
        $cfg = public_path($file_name);
        $res = fopen($cfg, "a+");
        fwrite($res,$secretGroup);
        fwrite($res,"\n\n");
        foreach ($list as $val) {
            fwrite($res, "Admin={$val['steamid']}:{$val['group']}\r\n");
        }
        fclose($res);
//        return self::response(["url" => URL::to('/') . "/{$file_name}"]);
        return self::response(["url" => env("APP_URL") . "/{$file_name}"]);
    }

    public function team_add($request){

        $params = $request->all();
        $gh_id = $params['gh_id'];
        $gh_secret = $params['gh_secret'];

        $dep = new TeamsDep();
        $res = $dep->check_exists($gh_id, $gh_secret);
        if (is_null($res)) {
            return self::response([], "工会ID与密钥不匹配", 2);
        }

        $data = [
          'current_map' => $params['current_map'],
          'next_map' => $params['next_map'],
          'next_time' => $params['next_time'],
        ];
        $dep->upd($res->id, $data);

        return self::response($data);

    }

}

